import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/widget/common/date_select.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import '../utils/utils.dart';

class NewEnterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<NewEnterPage> {
  TextEditingController _caseNoController = new TextEditingController();
  TextEditingController _caseNameController = new TextEditingController();
  TextEditingController _remarkController = new TextEditingController();
  String submittedDate = '';

  List storeList = [];
  int storeIndex;
  String storeName;
  List libraryList = [];
  int libraryIndex;
  int storeId;
  int libraryId;
  String libraryName;
  bool libraryLoadSuccess = false;
  List departmentList = [];
  String depName;
  int depId;
  String depUName;
  int depUId;

  @override
  void initState() {
    super.initState();
    getDepartment();
    getStoreList();
  }

  // 获取来源部门列表
  getDepartment() {
    DioUtils.request("common/getSourceDepartmentList",
        context: context, method: "GET", onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          departmentList = res['data'];
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  _nextStep() {
    String caseNo = _caseNoController.text.trim();
    String caseName = _caseNameController.text.trim();
    String remark = _remarkController.text.trim();

    // if(caseNo == '') {
    //   Utils.showText(text: '请输入案件编号'); return;
    // }

    if (caseName == '') {
      Utils.showText(text: '请输入入库名称');
      return;
    }

    if (depName == null) {
      Utils.showText(text: '请选择来源单位');
      return;
    }

    // if(storeName == null) {
    //   Utils.showText(text: '请选择存放仓库'); return;
    // }

    // if(libraryName == null) {
    //   Utils.showText(text: '请选择存放库区'); return;
    // }

    Navigator.pushNamed(context, "/add_material", arguments: {
      'case_no': '',
      'case_name': caseName,
      'department_id': depId,
      'submission_time': submittedDate,
      'store_id': '',
      'library_id': '',
      'remark': remark,
      'depUId': depUId
    });
  }

  Widget _buildInput(title, controller, [isNumber = false, maxLines = 1]) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 150.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              // textAlign: TextAlign.end,
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          Container(
            width: 510.w,
            height: maxLines > 1 ? 200.h : 40,
            child: TextField(
              inputFormatters: [
                FilteringTextInputFormatter.allow(
                    RegExp(isNumber ? '[0-9]' : '[^]')),
              ],
              maxLines: maxLines,
              controller: controller,
              style: TextStyle(fontSize: 14, color: Colors.black), //输入文本的样式
              decoration: InputDecoration(
                hintText: "请输入" + title,
                hintStyle: TextStyle(color: Color(0xFFC8C8D9), fontSize: 14),
                contentPadding: EdgeInsets.fromLTRB(21.w, 10, 21.w, 10),
                fillColor: Colors.white,
                filled: true,
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDateSelect(title) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: 150.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              // textAlign: TextAlign.end,
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          Container(
            width: 510.w,
            height: 40,
            decoration: BoxDecoration(
                color: Colors.white,
                border: new Border.all(
                    color: Utils.hexToColor('#D4D4D4'), width: 0.5),
                borderRadius: new BorderRadius.all(Radius.circular(8.w))),
            child: DateSelect(
              defaultDate: submittedDate,
              resetDate: () {
                setState(() {
                  submittedDate = '';
                });
              },
              onConfirm: (date) => {
                setState(() {
                  submittedDate = date;
                })
              },
            ),
          ),
        ],
      ),
    );
  }

  _buildSelectText(title, type, types) {
    Color colorOne = Utils.hexToColor('#333333');
    Color colorTwo = Utils.hexToColor('#C8C8D9');
    double fontSize = 14;

    if (type == 'unit') {
      if (types == 'dep') {
        return Text(depName != null ? depName : '请选择' + title,
            style: TextStyle(
                color: depName != null ? colorOne : colorTwo,
                fontSize: fontSize));
      } else {
        return Text(depUName != null ? depUName : '请选择' + title,
            style: TextStyle(
                color: depUName != null ? colorOne : colorTwo,
                fontSize: fontSize));
      }
    }
    if (type == 'store') {
      return Text(storeName != null ? storeName : '请选择' + title,
          style: TextStyle(
              color: storeName != null ? colorOne : colorTwo,
              fontSize: fontSize));
    }
    if (type == 'library') {
      return Text(libraryName != null ? libraryName : '请选择' + title,
          style: TextStyle(
              color: libraryName != null ? colorOne : colorTwo,
              fontSize: fontSize));
    }
  }

  Widget _buildSelectBox(title, type, BuildContext context, types) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 150.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              // textAlign: TextAlign.end,
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          GestureDetector(
              onTap: () {
                if (type == 'unit') {
                  showModalBottomSheet(
                      context: context,
                      builder: (BuildContext context) {
                        return new Container(
                            height: 400,
                            child: new ListView.builder(
                                padding: new EdgeInsets.all(5.0),
                                itemExtent: 50.0,
                                itemCount: departmentList.length,
                                itemBuilder: (BuildContext context, int index) {
                                  var item = departmentList[index];

                                  return new GestureDetector(
                                    onTap: () {
                                      print(
                                          '----------------------------------');
                                      print(types);
                                      if (types == 'dep') {
                                        setState(() {
                                          depId = item['id'];
                                          depName = item['name'];
                                        });
                                      } else {
                                        setState(() {
                                          depUId = item['id'];
                                          depUName = item['name'];
                                        });
                                      }

                                      Navigator.of(context).pop();
                                    },
                                    child: Container(
                                      decoration: BoxDecoration(
                                          border: Border(
                                              bottom: BorderSide(
                                                  color: Utils.hexToColor(
                                                      '#eeeeee')))),
                                      alignment: Alignment.centerLeft,
                                      padding: EdgeInsets.symmetric(
                                          vertical: 5, horizontal: 10),
                                      child: Text(item['name']),
                                    ),
                                  );
                                }));
                      });
                } else {
                  Scaffold.of(context).openEndDrawer();
                }
              },
              child: Container(
                  width: 510.w,
                  height: 40,
                  child: Container(
                      width: 510.w,
                      height: 40,
                      alignment: Alignment.centerRight,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        border: new Border.all(
                            color: Utils.hexToColor('#D4D4D4'), width: 0.5),
                        borderRadius:
                            new BorderRadius.all(Radius.circular(8.w)),
                      ),
                      child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: 21.w),
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                _buildSelectText(title, type, types),
                                Image.asset('assets/arrow_botton.png',
                                    width: 22)
                              ])))))
        ],
      ),
    );
  }

  Widget _buildSearchButton() {
    return Align(
      alignment: Alignment.centerRight,
      child: Container(
        width: 510.w,
        child: Align(
            alignment: Alignment.centerLeft,
            child: Container(
              width: 110,
              height: 35,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Utils.hexToColor('#297CFF'),
                  padding: EdgeInsets.all(0),
                ),
                onPressed: () {
                  _nextStep();
                },
                child: Text(
                  '下一步',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            )),
      ),
    );
  }

  Widget _buildCardTitle(title) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(bottom: 10.w, top: 10.w),
      child: Text(
        title,
        style: TextStyle(
            color: Utils.hexToColor('#333333'),
            fontSize: 24.w,
            fontWeight: FontWeight.bold,
            height: 1),
      ),
    );
  }

  // 获取仓库列表
  getStoreList() {
    setState(() {
      storeId = null;
      libraryId = null;
    });
    DioUtils.request("store/LibraryAddInstall",
        context: context, method: "POST", params: {}, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          storeList = res['data']['store'];
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 获取库区列表
  getLibraryList(id, libraryId, removeChildData) {
    setState(() {
      libraryLoadSuccess = false;
    });

    DioUtils.request("store/LibraryLists",
        context: context,
        method: "POST",
        params: {'store_id': id, 'limit': 100000}, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          libraryLoadSuccess = true;
          libraryList = res['data']['data'];
        });

        if (libraryId != null) {
          // 设置库区默认索引
          for (int i = 0; i < libraryList.length; i++) {
            var item = libraryList[i];
            if (libraryId == item['store_library_id']) {
              setState(() {
                libraryIndex = i;
              });
              break;
            }
          }
        }
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 设置仓库、库区
  setStores() {
    if (storeId == null) {
      Utils.showText(text: '请选择仓库');
      return;
    }

    if (libraryId == null) {
      Utils.showText(text: '请选择库区');
      return;
    }

    Navigator.of(context).pop();
  }

  // 构建仓库列表
  Widget _buildStoreCard() {
    List<Widget> content = [];

    for (int i = 0; i < storeList.length; i++) {
      var item = storeList[i];

      content.add(InkWell(
        onTap: () {
          setState(() {
            libraryId = null;
            libraryList = [];
            libraryIndex = null;
            storeIndex = i;
            storeId = item['store_id'];
            storeName = item['store_name'];
          });
          getLibraryList(item['store_id'], null, true);
        },
        child: Container(
          width: 290.w,
          height: 76.w,
          alignment: Alignment.center,
          color: Utils.hexToColor(storeIndex == i ? '#E7F3FF' : '#F8F8F8'),
          child: Text(
            item['store_name'],
            style: TextStyle(
                color:
                    Utils.hexToColor(storeIndex == i ? '#297CFF' : '#676767'),
                fontSize: 12,
                fontWeight:
                    storeIndex == i ? FontWeight.bold : FontWeight.w500),
          ),
        ),
      ));
    }

    return Container(
        padding: EdgeInsets.only(bottom: 15),
        margin: EdgeInsets.only(bottom: 15),
        decoration: BoxDecoration(
            border: Border(
                bottom:
                    BorderSide(width: 1, color: Utils.hexToColor('#F2F2F2')))),
        child: Wrap(
          spacing: 10.w,
          runSpacing: 10.w,
          crossAxisAlignment: WrapCrossAlignment.start,
          children: content,
        ));
  }

  // 构建库区列表
  Widget _buildLibraryCard() {
    List<Widget> content = [];

    if (libraryList.length > 0) {
      for (int i = 0; i < libraryList.length; i++) {
        var item = libraryList[i];

        content.add(InkWell(
          onTap: () {
            setState(() {
              libraryIndex = i;
              libraryId = item['store_library_id'];
              libraryName = item['library_name'];
            });
          },
          child: Container(
            width: 290.w,
            height: 76.w,
            alignment: Alignment.center,
            color: Utils.hexToColor(libraryIndex == i ? '#E7F3FF' : '#F8F8F8'),
            child: Text(
              item['library_name'],
              style: TextStyle(
                  color: Utils.hexToColor(
                      libraryIndex == i ? '#297CFF' : '#676767'),
                  fontSize: 12,
                  fontWeight:
                      libraryIndex == i ? FontWeight.bold : FontWeight.w500),
            ),
          ),
        ));
      }
    } else {
      if (storeIndex == null || libraryLoadSuccess == true) {
        content.add(Container(
          child: Text(
            storeIndex == null ? '请选择仓库' : '该仓库暂无库区',
            style: TextStyle(
              color: Utils.hexToColor('#676767'),
              fontSize: 12,
            ),
          ),
        ));
      } else {
        content.add(Container(
          child: Text(
            '加载中...',
            style: TextStyle(
              color: Utils.hexToColor('#676767'),
              fontSize: 12,
            ),
          ),
        ));
      }
    }

    return Container(
        padding: EdgeInsets.only(bottom: 15),
        margin: EdgeInsets.only(bottom: 15),
        decoration: BoxDecoration(
            border: Border(
                bottom:
                    BorderSide(width: 1, color: Utils.hexToColor('#F2F2F2')))),
        child: Wrap(
          spacing: 10.w,
          runSpacing: 10.w,
          crossAxisAlignment: WrapCrossAlignment.start,
          children: content,
        ));
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
        appBar: TopBar(
          title: '新建入库',
          actions: <Widget>[Text('')],
        ),
        body: Builder(builder: (BuildContext context) {
          return Container(
              padding: EdgeInsets.all(20),
              child: SingleChildScrollView(
                  child: Column(children: <Widget>[
                // _buildInput('案件编号', _caseNoController),
                _buildInput('入库名称', _caseNameController),
                _buildSelectBox('来源单位', 'unit', context, 'dep'),
                _buildSelectBox('联合执法单位', 'unit', context, 'depU'),
                _buildDateSelect('报送时间'),
                // _buildSelectBox('存放仓库', 'store', context),
                // _buildSelectBox('存放库区', 'library', context),
                _buildInput('工单备注', _remarkController, false, 5),
                _buildSearchButton()
              ])));
        }),
        endDrawer: Drawer(
            child: Container(
                color: Colors.white,
                padding: EdgeInsets.fromLTRB(20.w, 78.w, 20.w, 34.w),
                child: Stack(children: <Widget>[
                  SingleChildScrollView(
                    child: Column(children: <Widget>[
                      _buildCardTitle('仓库'),
                      _buildStoreCard(),
                      _buildCardTitle('库区'),
                      _buildLibraryCard(),
                      Container(
                        height: 50,
                      )
                      // _buildCard(),
                    ]),
                  ),
                  Align(
                      alignment: Alignment.bottomCenter,
                      child: Container(
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                            Container(
                                // margin: EdgeInsets.only(top: 70.w),
                                child: SizedBox(
                                    width: 550.w,
                                    height: 76.w,
                                    child: ElevatedButton(
                                      onPressed: () {
                                        setStores();
                                      },
                                      child: Container(
                                        margin: EdgeInsets.only(left: 16.w),
                                        child: Text(
                                          '确定',
                                          style: TextStyle(color: Colors.white),
                                        ),
                                      ),
                                      style: ElevatedButton.styleFrom(
                                          backgroundColor: Color(0xFF297CFF),
                                          shape: RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.circular(60.w))),
                                    )))
                          ])))
                ]))));
  }
}
